/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mygang.controller.batch;

import javax.servlet.http.HttpServletResponse;
import mygang.controller.AbstractController;
import mygang.helper.ControllerHelper;
import mygang.helper.JsonHelper;
import mygang.model.CustomResponse;
import mygang.service.manager.NewsService;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author eugene
 */
@Controller
@RequestMapping(AbstractController.BATCH)
public class RSSNewsController extends AbstractController {
    
    @Autowired
    private JobLauncher jobLauncher;
    @Autowired
    private Job newsImportJob;
    @Autowired
    private NewsService newsService;
    
    
    @RequestMapping("/")
    public ModelAndView loadNewsPage() {
        ModelAndView model = new ModelAndView(BATCH_NEWS);
        model.addObject("newsList", newsService.getNews());
        return model;
    }
    
    @RequestMapping(value = "/get_news", method = RequestMethod.POST)
    public void loadNews(@RequestParam(value = "url", required = true) String url, HttpServletResponse response) throws Exception {
        try {
            jobLauncher.run(
                newsImportJob,
                new JobParametersBuilder()
                    .addString("inputResource", url)
                    .toJobParameters()
            );
            
            JsonHelper.prepareJsonResponse(prepareSuccessfulResponse(url), response);
        } catch (Exception ex) {
            ControllerHelper.handleException(ex, response);
        }
    }
    
    private CustomResponse prepareSuccessfulResponse(String url) {
        return new CustomResponse(CustomResponse.Result.SUCCESS, 
            "", 
            "News by the '" + url + "' URL have been successfully loaded", 
            "News have been loaded");
    }
}
